import React, { useRef, useEffect } from 'react'
import * as echarts from 'echarts'

const axisOption = {
  textStyle: {
    color: '#333',
  },
  tooltip: {
    trigger: 'axis',
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLine: {
      lineStyle: {
        color: '#17b3a3',
      },
    },
    axisLabel: {
      interval: 0,
      color: '#333333',
    },
  },
  yAxis: [
    {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#17b3a3',
        },
      },
    },
  ],
  color: ['#2ec7c9', '#b6a2de', '#5ab1ef', '#ffb988', '#d87a83', '#8d98b3'],
  series: [],
}

const normalOption = {
  tooltip: {
    trigger: 'item',
  },
  color: [
    '#Bf78f4',
    '#dd536b',
    '#9462e5',
    '#a6a6a6',
    '#e1bb22',
    '#39c362',
    '#3ed1cf',
  ],
  series: []
}

const Echarts = ({ style, chartData, isAxisChart = true }) => {
  const echartRef = useRef()
  let echartObj = useRef(null)

  useEffect(() => {
    initChart()
  }, [chartData])

  const initChart = () => {
    echartObj.current = echarts.init(echartRef.current)
    if (isAxisChart) {
      axisOption.xAxis.data = chartData.xData;
      axisOption.series = chartData.series
      echartObj.current.setOption(axisOption)
    } else {
      normalOption.series = chartData.series
      echartObj.current.setOption(normalOption)
    }
  }

  return (
    <div style={style} ref={echartRef}></div>
  )
}

export default Echarts
